#include "camera/yuyv_camera.hpp"
#include "buffer/shared_frame_buffer.hpp"
#include "buffer/thread_safe_queue.hpp"
#include "buffer/frame.hpp"
#include "runner/puller/yuyv_camera_runner.hpp"
#include "runner/puller/RGARunner.hpp"
#include "rga/rga_converter.hpp"
#include "utils/log.hpp"


#include <iostream>
#include <signal.h>
#include <fstream>

void save_rgb_frame_as_raw(const std::shared_ptr<Frame>& frame, const std::string& filename) {
    std::ofstream ofs(filename, std::ios::binary);
    ofs.write(reinterpret_cast<const char*>(frame->data.data()), frame->data.size());
    ofs.close();
    LOG_INFO("保存 RGB888 原始图像: {}", filename);
}

int main(int argc, const char* argv[])
{


    InitLogger();

    // 初始化队列
    auto yuyv_queue = std::make_shared<ThreadSafeQueue<std::shared_ptr<Frame>>>(10);
    auto rgb_queue  = std::make_shared<ThreadSafeQueue<std::shared_ptr<Frame>>>(10);
    
    // 摄像头,色域转换对象
    YUYVCamera yuyvcamera("/dev/video41", 640, 480);
    RGAConverter rgaconverter(640, 480);

    // 运行线程
    YUYVCameraRunner yuyvcamerarunner(yuyvcamera, yuyv_queue);
    RGARunner rgarunner(rgaconverter, yuyv_queue, rgb_queue);

    yuyvcamerarunner.Start();
    rgarunner.Start();


    LOG_INFO("[System] yuyv 线程运行中，按 Ctrl+C 停止...");

    // 测试读取 10 帧 RGB888 图像并保存为 .rgb 文件
    for (int i = 0; i < 10; ++i) {
        auto frame = rgb_queue->Pop();
        if (frame && frame->format == FrameFormat::RGB) {
            std::string filename = "frame_" + std::to_string(i) + ".rgb";
            save_rgb_frame_as_raw(frame, filename);
        } else {
            LOG_ERROR("收到非 RGB 帧，跳过");
        }
    }



    LOG_INFO("\n[System] 正在停止服务...");
    yuyvcamerarunner.Stop();
    LOG_DEBUG("yuyvcamerarunner停止成功");
    rgarunner.Stop();
    LOG_DEBUG("rgarunner停止成功");


    LOG_INFO("[System] 程序已退出");

    return 0;
}
